package com.atguigu.app.dwd.db;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.util.KafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.util.Collector;

/**
 * @author hfh
 * @version 1.0
 * @date 2022/9/4 10:21
 */
public class DwdUserCartAdd {
    public static void main(String[] args) throws Exception {
        //获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //设置状态后端
        /*env.enableCheckpointing(5*60*1000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setCheckpointTimeout(3*60*1000L);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //TODO 从topic_db 中获取cart_info表数据
        String topicName = "topic_db";
        String groupId = "dwd_user_cart_add";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));

        //TODO 过滤出加购数据  type为‘insert’ 或者为‘update’and sku_num 为增加的数据
        SingleOutputStreamOperator<String> flatMap = streamSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    String type = jsonObject.getString("type");
                    String table = jsonObject.getString("table");
                    if ("cart_info".equals(table) && "insert".equals(type)) {
                        out.collect(jsonObject.toJSONString());
                    }
                } catch (Exception e) {
                }
            }
        });
        flatMap.print();

        flatMap.addSink(KafkaUtil.getKafkaProducer("dwd_user_cart_add"));

        env.execute(groupId);

    }
}
